package com.zp.business.impl.template;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.business.entity.template.TemplateMaster;
import com.zp.business.entity.template.bo.TemplateMasterBo;
import com.zp.business.entity.template.vo.TemplateMasterVo;
import com.zp.business.mapper.template.TemplateMasterMapper;
import com.zp.business.service.template.ITemplateMasterService;
import com.zp.common.core.constant.CacheNames;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.redis.utils.CacheUtils;
import com.zp.common.satoken.utils.LoginHelper;
import com.zp.system.api.entity.SysDept;
import com.zp.system.api.entity.SysUser;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 模板主记录Service业务层处理
 *
 * @author zhang peng
 * @ date 2024-04-08
 */
@RequiredArgsConstructor
@Service
public class TemplateMasterServiceImpl implements ITemplateMasterService {

    static Map<String, SysDept> sysDeptMap = CacheUtils.get(CacheNames.SYS_DEPT);
    /**
     * 用户信息
     */
    static Map<String, SysUser> sysUserMap = CacheUtils.get(CacheNames.SYS_USER);
    private final TemplateMasterMapper baseMapper;

    /**
     * 查询模板主记录
     */
    @Override
    public TemplateMasterVo queryById (String templateMasterId) {
        return baseMapper.selectVoById(templateMasterId);
    }

    /**
     * 查询模板主记录列表(分页)
     */
    @Override
    public TableDataInfo<TemplateMasterVo> queryPageList (TemplateMasterBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TemplateMaster> lqw = buildQueryWrapper(bo);
        Page<TemplateMasterVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(item -> {
            item.setStorageName(StringUtils.isNotBlank(item.getStorageId()) && CollectionUtil.isNotEmpty(sysDeptMap)
                    ? sysDeptMap.get(item.getStorageId()).getDeptName() : "");
            item.setUserName(StringUtils.isNotBlank(item.getUserId()) && CollectionUtil.isNotEmpty(sysUserMap)
                    ? sysUserMap.get(item.getUserId()).getNickName() : "");
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询模板主记录列表(不分页)
     */
    @Override
    public List<TemplateMasterVo> queryList (TemplateMasterBo bo) {
        LambdaQueryWrapper<TemplateMaster> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TemplateMaster> buildQueryWrapper (TemplateMasterBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TemplateMaster> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getType()), TemplateMaster::getType, bo.getType());
        // 非管理员登录可以查看所有的模板数据
        if (StringUtils.equals(LoginHelper.getLoginUser().getCustomerType(), "3")) {
            if (StringUtils.equals(bo.getAuthorityType(), "1")) {
                // 科室
                lqw.eq(TemplateMaster::getDeptId, bo.getDeptId());
                lqw.eq(TemplateMaster::getAuthorityType, "1");
            } else if (StringUtils.equals(bo.getAuthorityType(), "2")) {
                // 个人
                lqw.eq(TemplateMaster::getUserId, LoginHelper.getUserId());
                lqw.eq(TemplateMaster::getAuthorityType, "2");
            } else if (StringUtils.equals(bo.getAuthorityType(), "0")) {
                lqw.eq(TemplateMaster::getAuthorityType, "0");
            }
        } else {
            lqw.eq(StringUtils.isNotBlank(bo.getAuthorityType()), TemplateMaster::getAuthorityType, bo.getAuthorityType());
        }
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), TemplateMaster::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getItemClass()), TemplateMaster::getItemClass, bo.getItemClass());
        lqw.eq(StringUtils.isNotBlank(bo.getTitleInput()), TemplateMaster::getTitleInput, bo.getTitleInput());
        lqw.eq(StringUtils.isNotBlank(bo.getStartFlag()), TemplateMaster::getStartFlag, bo.getStartFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), TemplateMaster::getOrgId, bo.getOrgId());
        return lqw;
    }

    /**
     * 新增模板主记录
     */
    @Override
    public Boolean insertByBo (TemplateMasterBo bo) {
        bo.setUserId(LoginHelper.getUserId());
        TemplateMaster add = BeanUtil.toBean(bo, TemplateMaster.class);
        validEntityBeforeSave(add);
        add.initEntity();
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTemplateMasterId(add.getTemplateMasterId());
        }
        return flag;
    }

    /**
     * 修改模板主记录
     */
    @Override
    public Boolean updateByBo (TemplateMasterBo bo) {
        TemplateMaster update = BeanUtil.toBean(bo, TemplateMaster.class);
        update.updateInfo();
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave (TemplateMaster entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除模板主记录
     */
    @Override
    public Boolean deleteWithValidByIds (Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
